﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SocialPlatformSDK.Model;
using SocialPlatformSDK.Services.Util;
using System.IO.IsolatedStorage;
using SocialPlatformSDK.Services;
using SocialPlatformSDK.Util;

namespace SocialPlatformSDK.Controls
{
    /// <summary>
    /// OAuth 登录控件，用于 OAuth 授权，并返回 AccessToken 对象.
    /// </summary>
    public partial class OAuthLoginBrowser : UserControl
    {
        public static readonly DependencyProperty SocialNameProperty = 
            DependencyProperty.Register("SocialName", typeof(String), typeof(OAuthLoginBrowser), 
            null);

        public String SocialName
        {
            get { return (string)GetValue(SocialNameProperty); }
            set { SetValue(SocialNameProperty, value); }
        }

        private IOAuthService oAuthService =null;
        private IOAuthConfigruation OAuthConfigruation;
        private string callbackUrl ;
        private Action<Callback<AccessToken>> actionTokenCallback = null;
        private ISocialFactory socialFactory =null;
        private bool isCompleted = false;

        /// <summary>
        /// 构造函数.
        /// </summary>
        public OAuthLoginBrowser()
        {
            InitializeComponent();
            string socialname = SocialName;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();


        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if (SocialName != null && OAuthConfigruation==null)
            {
                oAuthService = FactoryHelper.GetOAuthServiceByName(SocialName);
                callbackUrl = oAuthService.GetCallBackUrl();
                socialFactory = FactoryHelper.GetSocialFactoryByName(SocialName);
                OAuthConfigruation = oAuthService.GetOAuthConfigruation();
            }
            return base.ArrangeOverride(finalSize);
           
        }
        /// <summary>
        /// 开始进行 OAuth 授权，若用户授权成功，则返回 AccessToken.
        /// </summary>
        /// <param name="actionTokenCallback">回调返回 AccessToken.</param>
        public void OAuthLogin(Action<Callback<AccessToken>> actionTokenCallback)
        {

            this.actionTokenCallback = actionTokenCallback;
            
            if (string.IsNullOrEmpty(OAuthConfigruation.APP_KEY))
            {
                MessageBox.Show("请输入ConsumerKey!");

                OnCallbackAccessToken(null);
                return;
            }

            if (string.IsNullOrEmpty(OAuthConfigruation.APP_SECRET))
            {
                MessageBox.Show("请输入ConsumerSecret!");

                OnCallbackAccessToken(null);
                return;
            }


            webBrowser1.Navigate(new Uri(OAuthConfigruation.Accredit));
             
        }

        

        private void webBrowser1_Navigating(object sender, Microsoft.Phone.Controls.NavigatingEventArgs e)
        {
            if (isCompleted)
            {
                //e.Cancel = true;
                return;
            }

            //第一次换取code
            if (!e.Uri.AbsoluteUri.Contains("code=") && !e.Uri.AbsoluteUri.Contains("code ="))
                return;


            isCompleted = true;
            var arguments = e.Uri.AbsoluteUri.Split('?');
            if (0 == arguments.Length)
            {
                return;
            }

            OAuthConfigruation.CodeToken.LoadToken(arguments[1]);
            oAuthService.GetAccessTokenRequest(OAuthConfigruation.CodeToken, (callback) =>
            {
                if (OAuthConfigruation.IfSaveAccessToken)
                {
                    OAuthConfigruation.AccessToken = callback.Data;
                    if (socialFactory != null)
                        socialFactory.SaveData(callback.Data);
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    if (actionTokenCallback != null)
                    {
                        actionTokenCallback(callback);
                    }
                });
            });
            
         
        }

        private void UserControl_SizeChanged_1(object sender, SizeChangedEventArgs e)
        {
            webBrowser1.Width = this.Width;
            webBrowser1.Height = this.Height;
        }

        private void OnCallbackAccessToken(AccessToken accessToken)
        {
            this.Dispatcher.BeginInvoke(() =>
                {
                    if (null != this.actionTokenCallback)
                    {
                        actionTokenCallback(new Callback<AccessToken>(accessToken != null, accessToken));
                    }
                });
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

    }
}
